<?php
include("../../news/model.php");

// ---------------------------------
// controller 
// ---------------------------------
// list every newss by (type, page_num, list_per_page)
// which define by url GET method
$type = NULL;
$page = NULL;
$list_per_page = 20;
$file_name = $_SERVER["PHP_SELF"];

if (array_key_exists("type", $_GET))
{
	$type = $_GET["type"];
}
if (array_key_exists("page", $_GET))
{
	$page = $_GET["page"];
}
else
{
	$page = 1;
}

$news_list = model_get_news_list($type, $page, $list_per_page);
array_walk($news_list, "set_edit_page");
array_walk($news_list, "set_delete_page");
$body_html = view_producnt_list($news_list);

$page_count = model_get_page_count($type, $list_per_page);
$body_html = $body_html . view_page_list($file_name, $page, $page_count, $type);

include("../template/layout.php");

// ---------------------------------
// model
// ---------------------------------
function set_edit_page(&$value, $key)
{
	$value["edit_page"] = "edit.php?id=" . $value["id"];
}

function set_delete_page(&$value, $key)
{
	$value["delete_page"] = "delete.php?id=" . $value["id"];
}

// ---------------------------------
// view
// ---------------------------------
function view_producnt_list($news_list)
{
	$news_list_html = "";
	$news_list_html = $news_list_html . "<!--news list start-->\n";
	$news_list_html = $news_list_html . "<div class='news_list'>\n";
	foreach ($news_list as $news)
	{
		$news_list_html = $news_list_html .
		view_news(
		$news["title"],
		$news["edit_page"],
		$news["delete_page"]
		);
	}
	$news_list_html = $news_list_html . "</div>\n";
	$news_list_html = $news_list_html . "<!--news list end-->\n";
	return $news_list_html;
}

function view_news($title, $edit_page, $delete_page)
{
	$news_html =
"<table class='news_intro'>
	<tr> <td class='news_title'>" . $title . "</td></tr>
	<tr> <td class='news_edit'><a href='" . $edit_page . "'>编辑</a></td> </tr>
	<tr> <td class='news_delete'><a href='" . $delete_page . "'>删除</a></td> </tr>
</table>";
	return $news_html;
}

function view_page_list($file_name, $page, $page_count, $type)
{
	$page_list_html = "";
	// 如果需要，显示上一页
	if ($page > 1)
	{
		if ($type)
		{
			$page_list_html = $page_list_html . sprintf("<a href=\"". $file_name ."?page=%d&type=%d\">上一页</a>", $page - 1, $type);
		}
		else
		{
			$page_list_html = $page_list_html . sprintf("<a href=\"". $file_name ."?page=%d\">上一页</a>", $page - 1);
		}
	}
	// 如果需要，显示下一页
	if ($page + 1 < $page_count)
	{
		if ($type)
		{
			$page_list_html = $page_list_html . sprintf("<a href=\"". $file_name ."?page=%d&type=%d\">下一页</a>", $page + 1, $type);
		}
		else
		{
			$page_list_html = $page_list_html . sprintf("<a href=\"". $file_name ."?page=%d\">下一页</a>", $page + 1);
		}
	}
	$page_list_html = $page_list_html . sprintf("%d/%d", $page, $page_count);
	return $page_list_html;
}
?>
